const config = require('./config')
const themeListeners = []
const dataListeners = {}

const data = {
  theme: 'light',
  hasLogin: false,
  openid: null,
  user: null,
  iconTabbar: '/page/weui/example/images/icon_tabbar.png',
  pxRatio: 2,
}
const proxyData = new Proxy(data, {
  // get: function(target, key) {
  //   return target[key]
  // },
  set: function(target, key, value) {
    const pre = target[key]
    target[key] = value
    if (dataListeners[key]) {
      dataListeners[key].forEach(i => i(value, pre))
    }
    return true
  }
})
App({
  
  onLaunch(opts, data) {
    console.log('App Launch', opts)
    // wx.hideTabBar()
    const { screenWidth, theme } = wx.getSystemInfoSync()
    this.globalData.theme = theme
    this.globalData.pxRatio = 750 / screenWidth
    if (data && data.path) {
      wx.navigateTo({
        url: data.path,
      })
    }
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: config.envId,
        traceUser: true,
      })
      this.getUser()
    }
  },

  
  onShow(opts) {
    console.log('App Show', opts)
    // console.log(wx.getSystemInfoSync())
  },
  onHide() {
    console.log('App Hide')
  },
  onThemeChange({ theme }) {
    this.globalData.theme = theme
    themeListeners.forEach((listener) => {
        listener(theme)
    })
  },
  watchThemeChange(listener) {
      if (themeListeners.indexOf(listener) < 0) {
          themeListeners.push(listener)
      }
  },
  unWatchThemeChange(listener) {
      const index = themeListeners.indexOf(listener)
      if (index > -1) {
          themeListeners.splice(index, 1)
      }
  },
  globalData: proxyData,
  watch(key, listener) {
    if (!dataListeners[key]) {
      dataListeners[key] = []
    }
    if (!dataListeners[key].includes(listener)) {
      dataListeners[key].push(listener)
    }
  },
  unWatch(key, listener) {
    const index = dataListeners[key]?.indexOf(listener)
    if (index > -1) {
      dataListeners[key].splice(index, 1)
    }
  },
  // lazy loading openid
  getUserOpenId(callback) {
    const self = this

    if (self.globalData.openid) {
      callback(null, self.globalData.openid)
    } else {
      wx.login({
        success(data) {
          wx.cloud.callFunction({
            name: 'login',
            data: {
              action: 'openid'
            },
            success: res => {
              console.log('拉取openid成功', res)
              self.globalData.openid = res.result.openid
              callback(null, self.globalData.openid)
            },
            fail: err => {
              console.log('拉取用户openid失败，将无法正常使用开放接口等服务', res)
              callback(res)
            }
          })
        },
        fail(err) {
          console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
          callback(err)
        }
      })
    }
  },
  // 通过云函数获取用户 openid，支持回调或 Promise
  getUserOpenIdViaCloud() {
    return wx.cloud.callFunction({
      name: 'wxContext',
      data: {}
    }).then(res => {
      this.globalData.openid = res.result.openid
      return res.result.openid
    })
  },
  getUser() {
    return wx.cloud.callFunction({
      name: 'user',
      data: {
        action: 'get'
      },
    })
    .then(res => {
      const user = res.result.data[0]
      this.globalData.user = user
      return user
    })
    .catch(e => console.error('getUser:',e))
  },
  registerUser(user) {
    return wx.cloud.callFunction({
      name: 'user',
      data: {
        action: 'insert',
        data: {
          ...user,
        }
      },
    })
    .then(res => {
      return this.getUser()
    })
    .catch(e => console.error('insertUser:',e))
  }
})

